package com.manlitech.manlichat.service.nettywebsocket;

import com.manlitech.manlichat.base.exception.MyException;
import com.manlitech.manlichat.base.netty.message.container.MessageHandler;
import com.manlitech.manlichat.base.netty.pool.MyChannelHandlerPool;
import com.manlitech.manlichat.base.netty.util.MessageSendUtil;
import com.manlitech.manlichat.dao.ChatMessageDao;
import com.manlitech.manlichat.dao.ImUserDao;
import com.manlitech.manlichat.dao.ImUserFriendDao;
import com.manlitech.manlichat.dto.ChatMessage;
import com.manlitech.manlichat.enums.ResultEnums;
import com.manlitech.manlichat.pojo.nettywebsocket.ChatToOneMessage;
import com.manlitech.manlichat.pojo.nettywebsocket.SeeMessage;
import com.manlitech.manlichat.service.ChatMessageService;
import com.manlitech.manlichat.util.ResultUtil;
import com.manlitech.manlichat.util.convert.ChatToOneMessageConvertToChatMessage;
import com.manlitech.manlichat.util.convert.SeeMessageConvertToChatMessage;
import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class SeeMessageHandler implements MessageHandler<SeeMessage> {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    MessageSendUtil messageSendUtil;

    @Autowired
    ChatMessageService chatMessageService;

    @Autowired
    ChatMessageDao chatMessageDao;

    @Autowired
    ImUserDao imUserDao;

    @Autowired
    ImUserFriendDao imUserFriendDao;

    @Override
    public void execute(Channel channel, SeeMessage message) {
        //判断是否绑定
        ChannelId fromChannel = MyChannelHandlerPool.channelIdMap.get(message.getFromId());
        if(fromChannel != null){
            //消息存入数据库
            //将我和你的聊天内容设置为已读
            chatMessageDao.executeUpdate(
                    "update chat_message set see = 1 " +
                            "where see != 1 " +
                            "and   from_id = ? " +
                            "and   to_id  = ? " , message.getFromId() , message.getToId() );
            messageSendUtil.sendToSomeone(message.getFromId(),message.getToId(),ResultUtil.success(message));
            return;
        }
        logger.error(ResultEnums.UN_AUTH.getMsg());
        //删除到channelGroup 通道组
        MyChannelHandlerPool.channelGroup.remove(channel);
        throw new MyException(ResultEnums.UN_AUTH);
    }

    @Override
    public String getType() {
        return SeeMessage.TYPE;
    }
}
